#include "imageuploader.h"
#include <QSettings>
#include <QCoreApplication>

ImageUploader::ImageUploader(QObject *parent) : QObject(parent)
{
    m_manager = new QNetworkAccessManager(this);
}

void ImageUploader::uploadImage(const QString &table, const QByteArray &imageData, const QString &suffix)
{
    // 重置状态
    m_lastUrl.clear();
    m_lastError.clear();

    // 构建JSON请求
    QJsonObject json;
    json["table"] = table;
    json["image"] = QString(imageData.toHex());
    json["suffix"] = suffix;

    QJsonDocument doc(json);
    QByteArray data = doc.toJson();

    QString congfig = QString();
#ifdef USE_PACKAGE_ENABLE
    congfig = QCoreApplication::applicationDirPath() + "/config/config.ini";
#else
    congfig = CONFIG_FILE_PATH;
#endif
    QSettings settings(congfig, QSettings::IniFormat);
    auto IP = settings.value("http/IP").toString();
    auto str_http = QString("%1/upload").arg(IP);

    // 发送请求
    QNetworkRequest request{QUrl(str_http)};
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QNetworkReply *reply = m_manager->post(request, data);
    connect(reply, &QNetworkReply::finished, this, [=]()
            { onUploadFinished(reply); });
}

void ImageUploader::onUploadFinished(QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError)
    {
        m_lastError = reply->errorString();
        qWarning() << "上传失败:" << m_lastError;
        emit uploadFailed(m_lastError);
        reply->deleteLater();
        return;
    }

    QByteArray response = reply->readAll();
    QJsonDocument doc = QJsonDocument::fromJson(response);

    if (doc.isNull())
    {
        m_lastError = "无效的JSON响应";
        qWarning() << "无效的JSON响应:" << response;
        emit uploadFailed(m_lastError);
        reply->deleteLater();
        return;
    }

    QJsonObject obj = doc.object();

    if (obj.contains("url") && obj["url"].isString())
    {
        m_lastUrl = obj["url"].toString();
        emit uploadFinished(m_lastUrl);
    }
    else if (obj.contains("error") && obj["error"].isString())
    {
        m_lastError = obj["error"].toString();
        qWarning() << "服务器错误:" << m_lastError;
        emit uploadFailed(m_lastError);
    }
    else
    {
        m_lastError = "无效的服务器响应";
        qWarning() << "无效的服务器响应:" << response;
        emit uploadFailed(m_lastError);
    }

    reply->deleteLater();
}